<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总记录数:20条
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>

          <el-button v-allow="'万人之上'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'一人之下'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="EmployeeList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="图片消失了"> -->
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="sortable" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页组件 -->
          <el-pagination
            :page-size="pageParams.size"
            layout="prev,pager,next"
            :total="total"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <addor-edit
        ref="refAdd"
        @update-employee="hupdateEmployee"
        @close="showDialog=false"
      />
    </el-dialog>
    <el-dialog
      :visible.sync="showDialogRole"
      title="新增员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- v-if="showDialogRole" -->
      <assign-role
        ref="assignRole"
        :employee-id="curEmployeId"
        @update-close="hUpdateClose"
        @close="showDialogRole=false"
      />
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empdialog'
import AssignRole from './assignRole.vue'
const obj = {}
EmployeeEnum.hireType.forEach(item => {
  obj[item.id] = item.value
})
export default {
  components: {
    'addor-edit': EmpDialog,
    AssignRole
  },
  data() {
    return {
      EmployeeList: [],
      showDialogRole: false,
      total: 0,
      pageParams: {
        size: 5,
        page: 1
      },
      showDialog: false,
      curEmployeId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log(res)
        this.EmployeeList = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载数据失败')
      }
    },
    formatEmployment(id) {
      return obj[id]
      // const type = EmployeeEnum.hireType.find(item => item.id === id)
      // return type.value
      // return id === 1 ? '正式' : '非正式'
    },
    // 点击页码
    hCurrentChange(curPage) {
      // console.log(curPage)
      this.pageParams.page = curPage
      this.loadEmployeeList()
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('删除', res)
        this.$message.success('删除成功')
        // 如果没有数据自动请求前一页数据
        if (this.EmployeeList.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (err) {
        console.log(err)
        this.$message.error('删除成功')
      }
    },
    // 删除
    hDel(id) {
      console.log('删除的id', id)
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 1. 去做删除
        this.doDel(id)
        // // 3. 更新页面- 重发请求
        // this.loadRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 收到子组件抛出的成功的事件
    hupdateEmployee() {
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 弹窗消失了清空表单数据
    hClose() {
      this.$refs.refAdd.resetForm()
    },
    async hExportExcel() {
      const res = await getEmployeeList(this.pageParams)
      console.log('我是res,我输出一下看看结果', res.data)
      const { header, data } = this.thtransData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header,
          data,
          // data: [
          //   ['刘备', 100],
          //   ['关羽', 500]
          // ],
          filename: 'excel-list',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    thtransData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const enkeys = Object.keys(rows[0])
      const header = enkeys.map(enkey => {
        return map[enkey]
      })
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },
    // 用户点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.curEmployeId = id
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    },
    hUpdateClose() {
      this.showDialogRole = false
      this.loadEmployeeList()
    }
  }
}
</script>
